package android.magical;

import java.util.GregorianCalendar;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class EventsFragment extends ListFragment{
	final String TAG = "EventsFragment";
	SimpleCursorAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
		View v = inflater.inflate(R.layout.events, container, false);
		TextView addEvent = (TextView) v.findViewById(android.R.id.empty);
		
		// Add event button when list is empty
		addEvent.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				FragmentManager fm = getActivity().getSupportFragmentManager();
        		FragmentTransaction tr = fm.beginTransaction();
        		
        		// Hide main content
        		View content = getActivity().findViewById(R.id.main_content);
        		Animation out = AnimationUtils.makeOutAnimation(getActivity(), true);
                content.startAnimation(out);
        		content.setVisibility(View.GONE);
        		
        		// Hide events
        		View events = getActivity().findViewById(R.id.events_fragment);
        		events.setVisibility(View.GONE);
        		
        		// Show AddEvent fragment
        		tr.add(R.id.event_container, new AddEventFragment());
        		tr.addToBackStack("viewEvent");
        		tr.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        		tr.commit();
			}
		});
		return v;
	}


	public void showEvents(int day, int month, int year){
		DatabaseControl db = ((MainActivity)getActivity()).getDatabase();
		String date = day+"/"+(month+1)+"/"+year;
		Log.v("showEvents", "date: " + date);
		Cursor cur = db.getItem(date);
		adapter = new SimpleCursorAdapter(getActivity().getApplicationContext(), R.layout.list_item, cur, new String[]{DatabaseControl.KEY_TIME, DatabaseControl.KEY_MESSAGE, DatabaseControl.KEY_OWNER}, new int[] {R.id.list_time, R.id.list_title, R.id.list_event_owner}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		adapter.setViewBinder(new EventsViewBinder());
		setListAdapter(adapter);
	}

	@Override
	public void onListItemClick (ListView l, View v, int position, long id){
		
		FragmentManager fm = getActivity().getSupportFragmentManager();
		FragmentTransaction tr = fm.beginTransaction();
		View content = ((MainActivity)getActivity()).findViewById(R.id.main_content);
		Animation out = AnimationUtils.makeOutAnimation(getActivity(), true);
        content.startAnimation(out);
		content.setVisibility(View.GONE);
		
		// Replace events with devices list
		tr.replace(R.id.events_fragment, new BluetoothFragment(),"bt");
		//tr.addToBackStack("bt");
		
		((MainActivity)getActivity()).updateEventsLabel("Devices list");

		// Add ViewEvent Fragment to the container
		ViewEventFragment viewEvent = new ViewEventFragment();
		Bundle args = new Bundle();
		LinearLayout listItem = (LinearLayout)v;
		String time = ((TextView)listItem.findViewById(R.id.list_time)).getText().toString();
		String message = ((TextView)listItem.findViewById(R.id.list_title)).getText().toString();
		String owner = (String) listItem.findViewById(R.id.list_event_owner).getTag();
		args.putString("time", time);
		args.putString("owner", owner);
		args.putString("message", message);
		args.putInt("id", (int)id);
		viewEvent.setArguments(args);
		tr.add(R.id.event_container, viewEvent);
		tr.addToBackStack("viewEvent");
		tr.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		tr.commit();
	}
	
	private class EventsViewBinder implements SimpleCursorAdapter.ViewBinder {

		public boolean setViewValue(View view, Cursor cursor, int id) {
			int viewId = view.getId();
			// Get dates
			GregorianCalendar chosenDate = ((MainActivity)getActivity()).getChosenDate();
			GregorianCalendar currentDate = new GregorianCalendar();
			switch(viewId) {
				case R.id.list_time:
					String time = cursor.getString(cursor.getColumnIndex(DatabaseControl.KEY_TIME));
					((TextView)view).setText(time);
					// Separate hours and minutes
					String[] hoursAndMinutes = ((String)time).split(":");
					// Set time for the event
					chosenDate.set(GregorianCalendar.HOUR_OF_DAY, Integer.parseInt(hoursAndMinutes[0]));
					chosenDate.set(GregorianCalendar.MINUTE, Integer.parseInt(hoursAndMinutes[1]));
					// Check if the current date is before the chosen date (true if they are the same as well)
					if(isDatePassed(chosenDate, currentDate)){
						((TextView)view).setTextColor(Color.parseColor("#313131"));
						((MainActivity)getActivity()).setDatePassed(true);
					}
					break;            
				case R.id.list_title:
					String title = cursor.getString(cursor.getColumnIndex(DatabaseControl.KEY_MESSAGE));
					((TextView)view).setText(title);
					if(((MainActivity)getActivity()).isDatePassed()){
						((TextView)view).setTextColor(Color.parseColor("#313131"));
						((MainActivity)getActivity()).setDatePassed(false);
					}
					break;
				case R.id.list_event_owner:
					String owner = cursor.getString(cursor.getColumnIndex(DatabaseControl.KEY_OWNER));
					Log.v(TAG, "owner: " + owner);
					if(owner.equals(((MainActivity)getActivity()).getOwnerName())) 
						((ImageView)view).setImageResource(R.drawable.personal_event);
					else 
						((ImageView)view).setImageResource(R.drawable.shared_event);
					view.setTag(owner);
					break;
			}
			return true;
		}
	}
	
	
	// Calendar.before() and after() don't seem to work properly. Use own method.
	private boolean isDatePassed(GregorianCalendar thisDate, GregorianCalendar otherDate){
		Log.v(TAG, "comparing " + thisDate.get(GregorianCalendar.DAY_OF_MONTH) + " and " + otherDate.get(GregorianCalendar.DAY_OF_MONTH));
		if(thisDate.get(GregorianCalendar.YEAR) < otherDate.get(GregorianCalendar.YEAR)){
			if(thisDate.get(GregorianCalendar.DAY_OF_MONTH) <= otherDate.get(GregorianCalendar.DAY_OF_MONTH)){
				// Same day - check time
				if(thisDate.get(GregorianCalendar.DAY_OF_MONTH) == 
						otherDate.get(GregorianCalendar.DAY_OF_MONTH)){
					// Today but passed
					if(thisDate.get(GregorianCalendar.HOUR_OF_DAY) < 
							otherDate.get(GregorianCalendar.HOUR_OF_DAY)){
						Log.v(TAG, "Result: Same day but passed(hours)");
						return true;
					} else if(thisDate.get(GregorianCalendar.HOUR_OF_DAY) == 
							otherDate.get(GregorianCalendar.HOUR_OF_DAY)){
						// Today but passed
						if(thisDate.get(GregorianCalendar.MINUTE) < 
								otherDate.get(GregorianCalendar.MINUTE)){
							Log.v(TAG, "Result: Same day but passed(hours and minutes)");
							return true;
						}			
					}
					// Today but not passed
					else {
						Log.v(TAG, "Result: Same day but not passed");
						return false;
					}
				}
				Log.v(TAG, "Result: Passed(day)");
				return true;
				// Otherwise - event has passed
			} 
			return true;
		}else {
			Log.v(TAG, "Result: Not passed");
			return false;
		}
	}

}
